package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.jaxrs.FastJsonAutoDiscoverable;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadUtil;
import com.heima.wemedia.controller.v1.WmNewsController;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    /**
     * 条件查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1.参数校验
        //分页校验
        dto.checkParam();

        //2.分页查询
        //分页
        IPage page = new Page(dto.getPage(),dto.getSize());

        //条件构造
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //状态精确查询
        if(dto.getStatus() != null){
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //频道精确查询
        if(dto.getChannelId() != null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }

        //关键字精确查询
        if(StringUtils.isNotBlank(dto.getKeyword())){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }

        //时间范围查询
        if(dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            wrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }

        //查询是否当前登陆人的文章
        if(WmThreadUtil.getUser().getId() != null){
            wrapper.eq(WmNews::getUserId,WmThreadUtil.getUser().getId());
        }

        //时间顺序查询
        wrapper.orderByDesc(WmNews::getPublishTime);

        IPage page1 = this.page(page, wrapper);

        //3.返回结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page1.getTotal());
        responseResult.setData(page1.getRecords());
        return responseResult;
    }

    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws InvocationTargetException, IllegalAccessException {
        //0.参数校验
        if(dto == null || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //1.保存或修改文章
        WmNews wmNews = new WmNews();
        //拷贝相同属性
        BeanUtils.copyProperties(dto,wmNews);

        //将dto中的图片集合，解析成字符串
        if(dto.getImages() != null && dto.getImages().size() > 0){
            String imagesStr = StringUtils.join(dto.getImages(), ",");
            //将wmNews中的字符串赋值
            wmNews.setImages(imagesStr);
        }

        //如果当前封面类型为-1
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }

        saveOrUpdateWmNews(wmNews);
        //2.判断是否为草稿，如果是草稿则结束方法
        if(dto.getStatus().equals(WemediaConstants.WM_CONTENT_REFERENCE)){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //3.不是草稿，保存内容图片与素材的关系
        //提取文章内容中的图片信息
        List<String> images = extractUtlInfContent(dto.getContent());

        saveRelativeInfoForContent(images,wmNews.getId());

        //4.不是草稿，保存封面图片与素材的关系，如果当前布局是自动，那么自动匹配封面图片。
        saveRelativeInfoForCover(dto,wmNews,images);


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 第一个功能，如果当前布局为自动，则设置封面类型的数据
     * 匹配规则：
     * 1. 如果图片内容大于等于1小于3 ， 单图， type = 1
     * 2. 如果图片内容大于等于3， 多图， type = 3
     * 3. 如果内容没有图片，无图， type = 0
     *
     * 第二个功能，保存封面图片与素材的关系
     * @param dto
     * @param wmNews
     * @param images
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, WmNews wmNews, List<String> images) {
        List<String> dtoImages = dto.getImages();

        //自动匹配
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            //单图
            if (images.size()>=1 && images.size()<3){
                wmNews.setType(WemediaConstants.WM_COVER_REFERENCE);
                dtoImages = images.stream().limit(1).collect(Collectors.toList());
            }
            //多图
            else if(images.size() > 3){
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                dtoImages = images.stream().limit(3).collect(Collectors.toList());
            }
            //无图
            else {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }

            if(dtoImages.size() >0 && dtoImages != null){
                //设置文章的封面图片属性
                wmNews.setImages(StringUtils.join(dtoImages,","));
            }
            //修改文章
            updateById(wmNews);

            if(dtoImages.size() >0 && dtoImages != null){
                saveRelativeInfo(dtoImages,wmNews.getId(),WemediaConstants.WM_COVER_REFERENCE);
            }




        }
    }

    /**
     * 处理文章内容图片与素材的关系
     * @param images
     * @param newsId
     */
    private void saveRelativeInfoForContent(List<String> images, Integer newsId) {
        saveRelativeInfo(images,newsId,WemediaConstants.WM_CONTENT_REFERENCE);
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 保存文章图片与素材的关系
     * @param images
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> images, Integer newsId, Short type) {

        if(images != null && !images.isEmpty()){
            //根据url查询id
            List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images));

            //判断素材是否有效
            if(wmMaterials == null || wmMaterials.size() == 0){
                //手动抛出异常  第一个功能，能够提示使用者素材引用失效，第二个功能，能够数据回滚
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);

            }

            if(wmMaterials.size() != images.size()){
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }

            List<Integer> materialIds = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());



            //批量保存
            wmNewsMaterialMapper.saveRelations(materialIds,newsId,type);

        }

    }

    /**
     * 提取文章内容图片信息
     * @param content
     * @return
     */
    private List<String> extractUtlInfContent(String content) {
        ArrayList<String> materials = new ArrayList<>();

        List<Map> maps = JSON.parseArray(content, Map.class);

        for(Map map:maps){
            if (map.get("type").equals("image")){
                String image = (String)map.get("value");
                materials.add(image);
            }
        }

        return materials;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 保存或修改文章
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补全属性
        wmNews.setUserId(WmThreadUtil.getUser().getId());
        wmNews.setEnable((short)1);
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());

        //判断保存还是修改
        if(wmNews.getId() == null){
            //保存
            this.save(wmNews);
        }else {
            //修改
            //删除文章图片与素材内容的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
            this.updateById(wmNews);

        }

    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 文章的上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.检查参数
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.查询文章
        WmNews wmNews = this.getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //3.判断文章是否发布
        if(!wmNews.getStatus().equals(9)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"当前文章不是发布状态，不能上下架");
        }

        //4.修改文章enable
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){
            this.update(Wrappers.<WmNews>lambdaUpdate().set(WmNews::getEnable,dto.getEnable())
                    .eq(WmNews::getId,wmNews.getId()));

            if(wmNews.getArticleId() != null){
                //发送消息，通知article修改文章配置
                HashMap<String, Object> map = new HashMap<>();
                map.put("articleId",wmNews.getArticleId());
                map.put("enable",wmNews.getEnable());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(map));
            }

        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
